<!--
 * @Date: 2022-04-12 14:43:30
 * @Author: 陶子
 * @LastEditTime: 2022-09-14 14:41:29
 * @FilePath: \jk_one-stop_cloud_mobile_v1.0\src\views\workManagement\productTask\report.vue
 * @pageName: 这是--(生产任务-报工)--页面
-->
<template>
  <div>
    <Navbar :appTitle="appTitle" />
    <div class="search-content wrap-apply" :style="{top: GLOBAL.currentEnvironment ? '0' : '',height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : ''}">
      <van-cell-group style="margin-top:0.1rem">
        <p class="label required FormTit"><span></span>工单编号</p>
        <scanInput ref="scanInput" :columns="columns" @changeScan="changeScan" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>生产物料</p>
        <van-field readonly v-model="buildForm.showProductName" placeholder="请先选择工单编号" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>工序</p>
        <van-field-select-picker :supportClear='true' label="" placeholder="请选择" v-model="buildForm.taskId" :columns="taskList"
          :option="{ label: 'text', value: 'value' }" @confirm="processConfim" @prePopShow="showProcessDialog" />
        <div class="bottomLine" style="margin-top:0.01rem"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>批次编号</p>
        <scanInput ref="scanBatch" placeholder="请选择或扫批次码" EntityType="batchCode" :columns="batchColumns" @changeScan="changeBatchScan" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>操作人</p>
        <!-- <van-field-select-picker label="" :supportClear='true' placeholder="请选择" v-model="buildForm.operatorId" :columns="operatorList"
          :option="{ label: 'text', value: 'value' }" @confirm="peopleConfirm" @prePopShow="showPeopleDialog" /> -->
          <van-field-checkbox
            :supportClear="true"
            placeholder="请选择"
            v-model="buildForm.operatorId"
            :columns="operatorList"
            :option="{ label: 'text', value: 'value' }"
          />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>合格数</p>
        <div class="haveUnitBox">
          <van-field v-model="buildForm.qualifiedNum" @input='formatInput("qualifiedNum",buildForm.qualifiedNum)'
            @blur='checkValue("qualifiedNum",buildForm.qualifiedNum)' placeholder="请输入" />
          <span>{{buildForm.processWorkUnitText}}</span>
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>不合格数</p>
        <div class="haveUnitBox">
          <van-field v-model="buildForm.notQualifiedNum" readonly @click="showUp" placeholder="请输入" />
          <!-- <van-field v-model="buildForm.notQualifiedNum" placeholder="请输入" @blur='checkValue("notQualifiedNum",buildForm.notQualifiedNum)'
            @input='formatInput("notQualifiedNum",buildForm.notQualifiedNum)' /> -->
          <span>{{buildForm.processWorkUnitText}}</span>
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label  FormTit"><span></span>不合格原因</p>
        <!-- <van-field v-model="buildForm.notQualifiedReasonText" readonly placeholder="请输入不合格数" /> -->
        <div style="color:c8c9cc;padding: 0.1rem 0.16rem;">{{buildForm.notQualifiedReasonText || '请输入不合格数'}}</div>
        <!-- <van-field-checkbox label="" :supportClear='true' placeholder="请选择" v-model="notQualifiedReason" :columns="dictOptions"
          :option="{ label: 'text', value: 'value' }" @confirm="resonConfirm" /> -->
      </van-cell-group>
      <van-cell-group style='margin-top:0.1rem'>
        <p class="label otherText">其他</p>
        <div class="bottomLine"></div>
        <p class="label">备注</p>
        <van-field v-model="buildForm.remark" rows="2" autosize label="" type="textarea" maxlength="500" placeholder="请输入备注" show-word-limit />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <upload iconType="fj" @fileChange="fileChange" :fileIds="attachment" />
      </van-cell-group>
      <div style="margin-top: 0.12rem">
        <Examine @submitProcess="submitProcess" @getUserState="getUserState" type="0" :key="examKey" id="MESS_TASK_REPORT_WORK_APPLY_FOR_PRODUCT" ref="examine" />
        <div style="height: 0.26rem"></div>
      </div>
<div class="search-bottoms">
      <van-button type="default" :loading="subLoading" class="btncancel" @click="btnConfirm('continue')">继续报工</van-button>
      <van-button type="default" :loading="subLoading" class="btnconfirm" @click="btnConfirm('finish')">提交</van-button>
    </div>
    </div>
    <not-qualified-num ref="NotQualifiedNum" :dataSource="dictOptions" @comfirm="comfirmReason"></not-qualified-num>
  </div>
</template>
<script>
import { ajaxGetDictItems } from "@/api/api";
import Navbar from "@/components/navBar/navBar_right";
import scanInput from "@/components/scanCode/scanInput";
import ContactPickers from "@/components/choiceuse/ContactPickers";
import upload from "@/components/upload/upload";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import VanFieldCheckbox from "@/components/ActionSheet/VanFieldCheckbox";
import { clearNoNum, accAdd, accSub, setTitle } from "@/utils/util";
import Examine from "@/components/examine";
import NotQualifiedNum from "@/components/choiceuse/NotQualifiedNum";
import {
  getOrderCodeDict,
  getProcessOptions,
  taskDetailApi,
  getReportTeamUserListByTaskId,
  workOrderDetailApi,
  recordAdd,
  queryBatchTaskReportList
} from "@/api/mobile";
export default {
  name: "search",
  components: {
    ContactPickers,
    upload,
    VanFieldSelectPicker,
    VanFieldCheckbox,
    Navbar,
    scanInput,
    Examine,
    NotQualifiedNum
  },
  data() {
    return {
      taskId: "",
      orderId: "",
      notQualifiedReason: "",
      subLoading: false,
      buildForm: {
        orderId: undefined,
        showProductName: "",
        taskId: "",
        excessCanReportNum: "",
        processWorkUnitText: "",
        operatorId: [],
        reportWorkNum: "",
        qualifiedNum: "",
        notQualifiedNum: "",
        remark: "",
        notQualifiedReason: "",
        notQualifiedReasonText: "",
      },
      dictOptions: [], //不合格原因
      defaultNQTable: [], //不合格原因
      createdByName: "", //操作人
      columns: [],
      workOrderList: [], //完整的工单编号列表
      taskList: [], //工序列表
      operatorList: [], //操作人
      attachment: "", //附件
      subimtType: "",
      examKey: 1,
      formPage: "",
      currentLoginUser: {},
      showPeopleSlect: false,
      copyCurrentData: [],
      batchColumns: [], // 批次编号下拉列表
      batchCodeList: [], // 批次编号下拉列表
      availableNumForReport: '',
      excessCanReportNum: '',
      qualifiedNumByUser: false,
      orderByBatch: true, // 默认工单工序由批次带出，选定工单时改为false
      taskByBatch: false, // 工序是否选择工单后由批次带出
      allBatchByOrder: [], // 选择工单后查出工单下所有批次，扫码时校验用
      appTitle: '生产报工',
      appTitleText: '生产报工',
    };
  },
  computed: {},
  beforeRouteLeave(to, from, next) {
    if (this.showPeopleSlect) {
      this.$refs.examine.closePicker();
      next(false);
    } if (this.$refs.NotQualifiedNum.show) {
      this.upDateTitle('生产报工')
      this.$refs.NotQualifiedNum.show = false
      next(false);
    } else {
      next();
    }
  },
  created() {
    this.currentLoginUser = JSON.parse(
      localStorage.getItem("pro__Login_Userinfo")
    ).value;
    this.taskId = this.$route.query.taskId;
    this.orderId = this.$route.query.orderId;
    this.getBatchList('created')
    ajaxGetDictItems("mess_not_qualified_reason", null).then((res) => {
      if (res.success) {
        this.dictOptions = res.result.map((item) => {
          let obj = {
            notQualifiedReasonText: item.text,
            notQualifiedReason: item.value,
            notQualifiedNum: ''
          }
          this.defaultNQTable.push(obj)
          return obj
        })
      }
    });
    let obj = {
      status: "inProduction",
      type: "production",
    };
    getOrderCodeDict(obj).then((res) => {
      if (res.success) {
        this.workOrderList = res.result;
        this.columns = [];
        for (let item of res.result) {
          let obj = {
            key: item.orderCode,
            value: item.id,
          };
          this.columns.push(obj);
        }
      } else {
        this.$toast(res.message);
      }
    });
    this.formPage = this.$route.query.formPage;
    if (this.formPage == "scanCode" && this.$route.query.code) {
      this.orderId = this.$route.query.code.id;
      this.changeScan({ code: this.$route.query.code }, "scan", "created");
    } else if (this.taskId) {
      this.getInitData();
    }
  },
  methods: {
    getBatchList(key) {
      let obj = {
        orderId: this.buildForm.orderId,
        taskId:this.buildForm.taskId,
        type:'production'
      }
      if (key == 'created') {
        obj = {
          orderId: this.orderId,
          taskId:this.taskId,
          type:'production'
        }
      }
      queryBatchTaskReportList(obj).then(res => {
        if (res.success) {
          this.batchCodeList = res.result;
          if (key == 'task'&& this.buildForm.batchId) { // 如果工序不是批次带出，切换工序时查看是否已选批次，已选批次的话，若新工序下有该批次则不用删除批次
            let bat = this.batchCodeList.find(b=> b.batchId == this.buildForm.batchId)
            if (bat) {
              return
            }
            this.clearBatch()
          }
          this.batchColumns = [];
          for (let item of res.result) {
            let obj = {
              key: item.batchCode,
              value: item.id,
            };
            this.batchColumns.push(obj);
          }
        } else {
          this.$toast(res.message);
        }
      })
    },
    upDateTitle(v) {
      this.appTitle = v
      setTitle(this.appTitle)
    },
    comfirmReason(obj, arr) {
      this.upDateTitle('生产报工')
      this.buildForm.notQualifiedReason = obj.notQualifiedReason
      this.buildForm.notQualifiedReasonText = obj.notQualifiedReasonText
      this.buildForm.notQualifiedNum = obj.notQualifiedNum
      this.dictOptions = arr
      this.checkValue("notQualifiedNum",this.buildForm.notQualifiedNum)
    },
    showUp() {
      this.upDateTitle('不合格数输入')
      this.$refs.NotQualifiedNum.showUp(this.dictOptions)
    },
    getUserState(v) {
      this.showPeopleSlect = v;
    },
    //页面加载请求数据
    getInitData() {
      let object = {
        id: this.orderId,
        type: "production",
      };
      getOrderCodeDict(object).then((res) => {
        if (res.success) {
          let item = res.result[0];
          this.buildForm.orderId = item.id;
          this.$refs.scanInput.propValue(item);
          this.buildForm.orderCode = item.orderCode;
          this.buildForm.showProductName =
            item.goodsCode + "-" + item.goodsName;
          this.orderCodeChange();
        } else {
          this.$toast(res.message);
        }
      });
    },
    orderCodeChange() {
      let obj = {
        orderId: this.buildForm.orderId,
        reportStatus: "yes",
        type: "production",
      };
      getProcessOptions(obj).then((res) => {
        if (res.success) {
          this.taskList = [];
          for (let item of res.result) {
            let gongObj = {
              text: `${item.processCode}-${item.processName}`,
              value: item.id,
            };
            this.taskList.push(gongObj);
          }
          for (let each of res.result) {
            if (each.id == this.taskId) {
              this.buildForm.taskId = each.id;
              let obj = {
                id: each.id,
              };
              this.getTaskDetail(obj);
            }
          }
        } else {
          this.$toast(res.message);
        }
      });
    },
    getTaskDetail(obj) {
      taskDetailApi(obj).then((res) => {
        if (res.success) {
          let item = res.result;

          this.availableNumForReport = item.availableNumForReport
          this.excessCanReportNum = item.excessCanReportNum

          this.buildForm.qualifiedNum = item.availableNumForReport;
          this.buildForm.excessCanReportNum = item.excessCanReportNum;
          this.buildForm.processWorkUnitText = item.processWorkUnitText;
          let taskObj = {
            taskId: this.buildForm.taskId,
          };
          getReportTeamUserListByTaskId(taskObj).then((res) => {
            if (res.success) {
              this.operatorList = res.result;
              for (let item of this.operatorList) {
                if (item.value == this.currentLoginUser.id) {
                  this.buildForm.operatorId = [item.value];
                }
              }
            } else {
              this.$toast(res.message);
            }
          });
        } else {
          this.$toast(res.message);
        }
        this.$forceUpdate();
      });
    },
    changeBatchScan(v, type) {
      console.log(v);
      this.buildForm.qualifiedNum = "";
      this.buildForm.reportWorkNum = "";
      this.buildForm.notQualifiedNum = "";
      this.notQualifiedReason = "";
      this.buildForm.notQualifiedReasonText = ''
      this.dictOptions = JSON.parse(JSON.stringify(this.defaultNQTable))
      let tasks = null
      if (type == "scan") {
        if (v.code.EntityType != "batchCode") {
          this.$toast("请扫正确二维码");
          return;
        }
        tasks = this.batchCodeList.find(item => item.batchId == v.code.id)
        if (!tasks&&this.buildForm.orderId&&!this.orderByBatch) {
          let open = this.allBatchByOrder.find(item => item.batchId == v.code.id)
          console.log('open:',open,'--','this.allBatchByOrder:',this.allBatchByOrder);
          console.log('open:',open,'this.buildForm.orderId:',this.buildForm.orderId);
          if (v.code.orderId != this.buildForm.orderId) { // 扫的批次所属工单id与当前工单id不匹配
            this.$toast("批次不是当前工单下的");
            return;
          }
          console.log(`批次在当前工单工序无可报工信息:${v.code.orderId}==${this.buildForm.orderId}&& ${!open} && ${this.buildForm.taskId}`);
          if (v.code.orderId == this.buildForm.orderId && open && this.buildForm.taskId) { // 已选工单工序，批次在工单下但不在可报工批次内
            this.$toast("批次在当前工单工序无可报工信息");
            return;
          }
          // if (!open || open.orderId != this.buildForm.orderId) {
          //   this.$toast("批次不是当前工单下的");
          //   return;
          // }
          // console.log(`批次不是当前工序下的1:${open} && ${this.buildForm.taskId}`);
          // if (open && this.buildForm.taskId) {
          //   let inTask = open.batchTaskList.find(ta => ta.taskId == this.buildForm.taskId)
          //   console.log('批次不是当前工序下的2:',inTask);
          //   if (!inTask) { // 已选工单工序，扫的批次在工单下但不在工序下
          //     this.$toast("批次不是当前工序下的");
          //     return;
          //   }
          // }
        }
        if (!tasks && this.orderByBatch) { // 未选择工单工序，扫的批次不在可报工批次列表内
          this.$toast("当前批次无可报工信息");
          return;
        }
        // if (tasks.batchTaskList.length == 0&&this.buildForm.orderId&&!this.orderByBatch) {
        //   this.$toast("批次在当前工单工序无可报工信息");
        //   return;
        // }
        this.qualifiedNumByUser = false
        this.buildForm.batchId = v.code.id;
        let batchObj = {
          id: v.code.id,
          orderCode: tasks.batchCode,
        };
        this.$refs.scanBatch.propValue(batchObj);
        let orderObj = {
          id: tasks.orderId,
          orderCode: tasks.orderCode,
        };
        this.$refs.scanInput.propValue(orderObj);
      } else {
        this.qualifiedNumByUser = false
        if (!v) {
          this.clearBatch()
          if (!this.orderByBatch) {
            // 删除批次-如果工序不是批次带出的，需要根据工单重置工序列表
            this.taskListByOrder()
          }
          this.dictOptions = JSON.parse(JSON.stringify(this.defaultNQTable))
          this.buildForm.notQualifiedNum = ''
          this.buildForm.notQualifiedReasonText = ''
          this.buildForm.notQualifiedReason = ''
          this.buildForm.availableNumForReport = this.buildForm.taskId ? this.availableNumForReport : ''
          this.buildForm.excessCanReportNum = this.buildForm.taskId ? this.excessCanReportNum : ''
          this.buildForm.qualifiedNum = this.buildForm.taskId ? this.availableNumForReport : ''
          return
        }
        this.buildForm.batchId = v.value
        tasks = this.batchCodeList.find(item => item.batchId == v.value)
      }
      let { orderId, taskId } = this.buildForm
      if (this.orderByBatch) {
        let scanObj = {
          id: tasks.orderId,
          orderCode: tasks.orderCode,
        };
        this.$refs.scanInput.propValue(scanObj);
        this.buildForm.orderId = tasks.orderId;
        this.buildForm.orderCode = tasks.orderCode;
        workOrderDetailApi({id: tasks.orderId}).then((res) => {
          if (res.success) {
            if (res.result && res.result.status == "inProduction") {
              this.buildForm.showProductName =
                res.result.goodsCode + "-" + res.result.goodsName;
            }
          }
        })
      }
      if (!orderId&&!taskId) {
        // let scanObj = {
        //   id: tasks.orderId,
        //   orderCode: tasks.orderCode,
        // };
        // this.$refs.scanInput.propValue(scanObj);
        // this.buildForm.orderId = tasks.orderId;
        // this.buildForm.orderCode = tasks.orderCode;
        // workOrderDetailApi({id: tasks.orderId}).then((res) => {
        //   if (res.success) {
        //     if (res.result && res.result.status == "inProduction") {
        //       this.buildForm.showProductName =
        //         res.result.goodsCode + "-" + res.result.goodsName;
        //     }
        //   }
        // })
        if (tasks.batchTaskList.length > 0) {
          this.setTaskInfoByBatch(tasks)
        }
      } else if (orderId&&!taskId) {
        this.setTaskInfoByBatch(tasks)
      } else if (orderId&&taskId) {
        console.log(tasks,this.batchCodeList);
        let task = tasks.batchTaskList[0];
        if (this.orderByBatch || this.taskByBatch) {
          console.log('要换工序了');
          this.setTaskInfoByBatch(tasks)
        } else {
          this.checkBatchWithTask(task)
        }
        // 对比批次和工序的可报工数begin
        // this.checkBatchWithTask(task)
        // 对比批次和工序的可报工数end
      }
    },
    clearBatch() {
      this.buildForm.batchId = ''
      this.buildForm.batchCode = ''
      let batchObj = {
        id: '',
        orderCode: '',
      };
      this.$refs.scanBatch.propValue(batchObj);
    },
    checkBatchWithTask(task) {
      if (task.availableNumForReport <= this.availableNumForReport) {
        this.buildForm.availableNumForReport = task.availableNumForReport > 0 ? task.availableNumForReport : ''
        this.buildForm.excessCanReportNum = task.excessCanReportNum
        this.buildForm.qualifiedNum = task.availableNumForReport
      } else if (task.availableNumForReport > this.availableNumForReport) {
        this.buildForm.availableNumForReport = this.availableNumForReport
        this.buildForm.excessCanReportNum = this.excessCanReportNum
        this.buildForm.qualifiedNum = this.availableNumForReport
      }
    },
    setTaskInfoByBatch(tasks) {
      this.taskList = [];
      this.taskList = tasks.batchTaskList.map((ta) => {
        ta.text = `${ta.processCode}-${ta.processName}`
        ta.value = ta.taskId
        return ta
      })
      console.log('新工序：',this.taskList);
      let task = tasks.batchTaskList[0];
      console.log(task,'task');
      this.buildForm.taskId = task.taskId;
      if (!this.orderByBatch) {
        this.taskByBatch = true
      }
      
      taskDetailApi({id: task.taskId}).then((res) => {
        if (res.success) {
          let item = res.result;
          
          this.availableNumForReport = item.availableNumForReport
          this.excessCanReportNum = item.excessCanReportNum

          this.buildForm.qualifiedNum = task.availableNumForReport;
          this.buildForm.excessCanReportNum = task.excessCanReportNum;
          this.buildForm.processWorkUnitText = item.processWorkUnitText;
          // 对比批次和工序的可报工数begin
          this.checkBatchWithTask(task)
          // 对比批次和工序的可报工数end
          this.$forceUpdate();
        } else {
          this.$toast(res.message);
        }
      });
      this.buildForm.operatorId = [];
      this.operatorList = [];
      let taskObj = {
        taskId: task.taskId,
      };
      getReportTeamUserListByTaskId(taskObj).then((res) => {
        if (res.success) {
          this.operatorList = res.result;
          for (let item of this.operatorList) {
            if (item.value == this.currentLoginUser.id) {
              this.buildForm.operatorId = [item.value];
            }
          }
        } else {
          this.$toast(res.message);
        }
      });
    },
    taskListByOrder() {
      this.taskList = [];
      let obj = {
        orderId: this.buildForm.orderId,
        reportStatus: "yes",
        type: "production",
      };
      getProcessOptions(obj).then((res) => {
        if (res.success) {
          for (let item of res.result) {
            let gongObj = {
              text: `${item.processCode}-${item.processName}`,
              value: item.id,
            };
            this.taskList.push(gongObj);
          }
        } else {
          this.$toast(res.message);
        }
      });
    },
    getAllBatchByOrder() {
      let obj = {
        orderId: this.buildForm.orderId,
        type:'production'
      }
      queryBatchTaskReportList(obj).then(res => {
        if (res.success) {
          this.allBatchByOrder = res.result;
        } else {
          this.$toast(res.message);
        }
      })
    },
    changeScan(v, opratorType, created) {
      if (created == 'created') {
        this.getBatchList('created')
      }
      console.log(v, "获取扫码组件数据");
      //value是下拉选择后值,code是扫码获得的值，根据qrcode判断是否隐藏当前页面只显示相机页
      if (opratorType == "select" && this.buildForm.orderId != v.value) {
        this.buildForm.orderId = v.value;
        this.getAllBatchByOrder()
        this.orderByBatch = false
        for (let item of this.workOrderList) {
          if (item.id == v.value) {
            this.buildForm.orderCode = item.orderCode;
            this.buildForm.showProductName =
              item.goodsCode + "-" + item.goodsName;
          }
        }
        this.buildForm.taskId = "";
        this.taskByBatch = false
        this.clearBatch(); // 清除批次
        this.getBatchList(); // 根据工单加载批次
        this.dictOptions = JSON.parse(JSON.stringify(this.defaultNQTable))
        this.buildForm.excessCanReportNum = "";
        this.buildForm.processWorkUnitText = "";
        this.buildForm.operatorId = [];
        this.operatorList = [];
        this.buildForm.reportWorkNum = "";
        this.buildForm.qualifiedNum = "";
        this.buildForm.notQualifiedNum = "";
        this.notQualifiedReason = "";
        this.taskListByOrder()
      }
      if (opratorType == "scan") {
        if (v.code.EntityType != "workOrder") {
          this.$toast("请扫正确二维码");
          return;
        }
        this.buildForm.orderId = v.code.id;
        this.getAllBatchByOrder()
        let obj = {
          id: v.code.id,
        };
        workOrderDetailApi(obj).then((res) => {
          if (res.success) {
            if (res.result && res.result.status == "inProduction") {
              this.buildForm.orderCode = res.result.orderCode;
              let scanObj = {
                id: this.buildForm.orderId,
                orderCode: res.result.orderCode,
              };
              this.$refs.scanInput.propValue(scanObj);
              this.buildForm.showProductName =
                res.result.goodsCode + "-" + res.result.goodsName;
              this.taskList = [];
              this.buildForm.taskId = "";
              this.buildForm.excessCanReportNum = "";
              this.buildForm.processWorkUnitText = "";
              this.buildForm.operatorId = [];
              this.operatorList = [];
              this.buildForm.reportWorkNum = "";
              this.buildForm.qualifiedNum = "";
              this.buildForm.notQualifiedNum = "";
              this.notQualifiedReason = "";
              let obj = {
                orderId: this.buildForm.orderId,
                reportStatus: "yes",
                type: "production",
              };
              getProcessOptions(obj).then((res) => {
                if (res.success) {
                  for (let item of res.result) {
                    let gongObj = {
                      text: `${item.processCode}-${item.processName}`,
                      value: item.id,
                    };
                    this.taskList.push(gongObj);
                  }
                } else {
                  this.$toast(res.message);
                }
              });
            } else {
              this.$toast("当前工单无法报工");
            }
          } else {
            this.$toast(res.message);
          }
        });
      }
    },
    resonConfirm(a) {
      if (a) {
        this.notQualifiedReason = a;
      } else {
        this.notQualifiedReason = "";
      }
    },
    fileChange(ids) {
      this.attachment = ids;
      console.log("父组件" + ids); //你要保存的fileids
    },
    // 工序选择确定
    processConfim(itemProcess) {
      if (itemProcess) {
        this.qualifiedNumByUser = false
        if (this.buildForm.taskId != itemProcess.value) {
          this.buildForm.taskId = itemProcess.value;
          if (!this.orderByBatch && !this.taskByBatch) {
            this.getBatchList('task')
          }
          let obj = {
            id: itemProcess.value,
          };
          taskDetailApi(obj).then((res) => {
            if (res.success) {
              let item = res.result;
              
              this.availableNumForReport = item.availableNumForReport
              this.excessCanReportNum = item.excessCanReportNum

              this.buildForm.qualifiedNum = item.availableNumForReport;
              this.buildForm.excessCanReportNum = item.excessCanReportNum;
              this.buildForm.processWorkUnitText = item.processWorkUnitText;
              if (this.orderByBatch && this.buildForm.batchId || this.taskByBatch) {
                let tasks = this.batchCodeList.find(bat => bat.batchId == this.buildForm.batchId)
                let task = {}
                if (tasks.batchTaskList.length > 0) {
                 task = tasks.batchTaskList.find(tb => tb.taskId == itemProcess.value)
                }
                this.checkBatchWithTask(task)
                console.log('this.checkBatchWithTask(task)');
                return
              }
              this.$forceUpdate();
            } else {
              this.$toast(res.message);
            }
          });
          this.buildForm.operatorId = [];
          this.operatorList = [];
          this.buildForm.reportWorkNum = "";
          this.buildForm.notQualifiedNum = "";
          this.notQualifiedReason = "";
          let taskObj = {
            taskId: this.buildForm.taskId,
          };
          getReportTeamUserListByTaskId(taskObj).then((res) => {
            if (res.success) {
              this.operatorList = res.result;
              for (let item of this.operatorList) {
                if (item.value == this.currentLoginUser.id) {
                  this.buildForm.operatorId = [item.value];
                }
              }
            } else {
              this.$toast(res.message);
            }
          });
        }
      } else {
        this.buildForm.taskId = "";
        this.buildForm.operatorId = [];
        this.operatorList = [];
        this.buildForm.qualifiedNum = "";
        this.buildForm.reportWorkNum = "";
        this.buildForm.notQualifiedNum = "";
        this.buildForm.excessCanReportNum = "";
        this.buildForm.processWorkUnitText = "";
        this.notQualifiedReason = "";
        if (!this.orderByBatch&&!this.taskByBatch) {
          // 删除工序-如果工序不是批次带出则根据工单重置批次和工序
          this.getBatchList()
          this.clearBatch()
          this.taskListByOrder()
        }
      }
    },
    //显示工序弹框选择
    showProcessDialog(callback) {
      if (!this.buildForm.orderId) {
        this.$toast("请先选择工单编号");
        callback("notShow");
      } else {
        if (this.taskList.length > 0) {
          callback("show");
        } else {
          this.$toast("该工单下暂无工序可报工");
          callback("notShow");
        }
      }
    },
    peopleConfirm(itemPeople) {
      if (itemPeople) {
        if (itemPeople.value) {
          this.buildForm.operatorId = [itemPeople.value];
        }
      } else {
        this.buildForm.operatorId = [];
      }
    },
    showPeopleDialog(callback) {
      if (!this.buildForm.taskId) {
        this.$toast("请先选择工序");
        callback("notShow");
      } else {
        callback("show");
      }
    },
    // 提交
    btnConfirm(subimtType) {
      this.subimtType = subimtType;
      if (!this.buildForm.orderId) {
        this.$toast("请选择工单编号");
        return;
      }
      if (!this.buildForm.taskId) {
        this.$toast("请选择工序");
        return;
      }
      if (!this.buildForm.operatorId || this.buildForm.operatorId.length == 0) {
        this.$toast("请选择操作人");
        return;
      }
      if (!Number(this.buildForm.notQualifiedNum) && !Number(this.buildForm.qualifiedNum)) {
        this.$toast("请输入合格数或不合格数");
        return;
      }
      // if (
      //   this.buildForm.notQualifiedNum > 0 &&
      //   this.notQualifiedReason.length == 0
      // ) {
      //   this.$toast("不合格数大于0时，不合格原因必填");
      //   return;
      // }
      this.submitProcess();
    },
    submitProcess(e) {
      if (e && e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.subLoading = true
        this.handleSubmit(e);
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm();
      }
    },
    handleSubmit(processDataVo) {
      let params = {
        ...this.buildForm,
        attachment: this.attachment,
        type: "production",
        processDataVo: processDataVo,
      };
      params.operatorId = params.operatorId.join(',')
      console.log("检查一下参数：", params);
      recordAdd(params).then((res) => {
        if (res.success) {
          this.subLoading = false
          this.$toast("报工成功");
          if (this.subimtType == "continue") {
            this.continueFun();
          } else {
            if (this.formPage == "scanCode") {
              this.$router.push("/dashboard/analysis");
            } else {
              this.$router.go(-1);
            }
          }
          this.subimtType = "";
        } else {
          this.subLoading = false
          this.$toast(res.message);
        }
      });
    },
    continueFun() {
      this.examKey += 1;
      this.taskList = [];
      this.buildForm.excessCanReportNum = "";
      this.buildForm.processWorkUnitText = "";
      this.buildForm.operatorId = [];
      this.operatorList = [];
      this.buildForm.reportWorkNum = "";
      this.buildForm.qualifiedNum = "";
      this.buildForm.notQualifiedNum = "";
      this.buildForm.remark = "";
      this.attachment = "";
      this.notQualifiedReason = "";
      let obj = {
        orderId: this.buildForm.orderId,
        reportStatus: "yes",
        type: "production",
      };
      getProcessOptions(obj).then((res) => {
        if (res.success) {
          for (let item of res.result) {
            let gongObj = {
              text: `${item.processCode}-${item.processName}`,
              value: item.id,
            };
            this.taskList.push(gongObj);
          }
          let isExist = false;
          for (let item of this.taskList) {
            if (item.value == this.buildForm.taskId) {
              isExist = true;
            }
          }
          if (!isExist) {
            this.buildForm.taskId = "";
          } else {
            let obj = {
              id: this.buildForm.taskId,
            };
            taskDetailApi(obj).then((res) => {
              if (res.success) {
                let item = res.result;
                this.buildForm.qualifiedNum = item.availableNumForReport;
                this.buildForm.excessCanReportNum = item.excessCanReportNum;
                this.buildForm.processWorkUnitText = item.processWorkUnitText;
                this.$forceUpdate();
              } else {
                this.$toast(res.message);
              }
            });
            let taskObj = {
              taskId: this.buildForm.taskId,
            };
            getReportTeamUserListByTaskId(taskObj).then((res) => {
              if (res.success) {
                this.operatorList = res.result;
                for (let item of this.operatorList) {
                  if (item.value == this.currentLoginUser.id) {
                    this.buildForm.operatorId = [item.value];
                  }
                }
              } else {
                this.$toast(res.message);
              }
            });
          }
          this.$forceUpdate();
        } else {
          this.$toast(res.message);
        }
      });
    },
    checkValue(type, value, bl) {
      if (type == "qualifiedNum") {
        this.qualifiedNumByUser = bl ? false : true
        let num = accSub(
          Number(this.buildForm.excessCanReportNum),
          Number(
            this.buildForm.notQualifiedNum ? this.buildForm.notQualifiedNum : 0
          )
        );
        if (Number(value) > Number(num)) {
          this.buildForm[type] = "0";
          this.buildForm.reportWorkNum = this.buildForm.notQualifiedNum;
          this.$toast("报工总数不能大于最大应生产数！");
        } else {
          if (this.buildForm.notQualifiedNum) {
            this.buildForm.reportWorkNum = accAdd(
              Number(this.buildForm.notQualifiedNum),
              Number(this.buildForm.qualifiedNum)
            );
          } else {
            this.buildForm.reportWorkNum = this.buildForm.qualifiedNum;
          }
        }
      } else {
        let num = accSub(
          Number(this.buildForm.excessCanReportNum),
          Number(this.buildForm.qualifiedNum ? this.buildForm.qualifiedNum : 0)
        );
        let qnum = accSub(
          Number(this.buildForm.excessCanReportNum),
          Number(value)
        );
        if (Number(value) > Number(num)) {
          if (!this.qualifiedNumByUser) {
            this.buildForm.qualifiedNum = Number(qnum) > 0 ? qnum : 0
          }
          let report = accAdd(
            Number(value),
            Number(this.buildForm.qualifiedNum)
          )
          if (this.buildForm.batchId || this.qualifiedNumByUser) {
            this.buildForm.reportWorkNum = report > this.buildForm.excessCanReportNum ? '' : report
            if (report > this.buildForm.excessCanReportNum) {
              this.dictOptions = JSON.parse(JSON.stringify(this.defaultNQTable))
              this.buildForm.notQualifiedNum = ''
              this.buildForm.notQualifiedReasonText = ''
              this.buildForm.notQualifiedReason = ''
              this.$toast('报工总数不能大于最大应生产数！')
              return
            }
          } else {
            if (report > this.buildForm.excessCanReportNum) {
              this.dictOptions = JSON.parse(JSON.stringify(this.defaultNQTable))
              this.buildForm.notQualifiedNum = ''
              this.buildForm.notQualifiedReasonText = ''
              this.buildForm.notQualifiedReason = ''
              this.$toast('报工总数不能大于最大应生产数！')
              return
            }
            this.buildForm.reportWorkNum = report
          }
        } else {
          if (this.buildForm.qualifiedNum) {
            this.buildForm.reportWorkNum = accAdd(
              Number(this.buildForm.notQualifiedNum),
              Number(this.buildForm.qualifiedNum)
            );
          } else {
            this.buildForm.reportWorkNum = this.buildForm.notQualifiedNum;
          }
        }
      }
    },
    formatInput(type, value) {
      this.buildForm[type] = clearNoNum(value);
      this.checkValue("qualifiedNum",this.buildForm.qualifiedNum, true)
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
.search-content {
  //  padding-bottom: 0.5rem;
  position: fixed;
  top: 0.42rem;
  width: 100%;
  height: calc(100vh - 1.12rem);
  background: #f5f5f5;
  overflow: scroll;
  z-index: 99;
  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
}
.bottomLine {
  height: 0.01rem;
  background-color: #f0f0f0;
  margin: 0 0.16rem;
}
.otherText {
  padding-bottom: 0.16rem;
  font-size: 0.16rem;
  font-weight: bold;
  color: #191f25;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 0.16rem;
  /deep/ .van-cell {
    padding-right: 0;
    width: 2.6rem;
  }
  /deep/ .van-field__control {
    max-width: 3rem;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
.search-bottoms {
  width: 100%;
  height: 0.5rem;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0px;
  padding: 0rem 0.11rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  font-weight: 500;
  z-index: 9;
  .btncancel {
    flex: 1;
    background: #f6f6f6;
    // border: 0.01rem solid rgba(25, 31, 37, 0.12);
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    margin-right: 0.11rem;
    color: #191f25;
  }
  .btnconfirm {
    flex: 1;
    background: #1890ff;
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    color: #ffffff;
  }
}
</style>
